using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Dimebrain.TweetSharp.Core.Extensions;
using Dimebrain.TweetSharp.Extensions;
using Dimebrain.TweetSharp.Fluent;

namespace twimillar2
{
	public static class Extensions
	{
		public static IList<string> GetFriends(this string person)
		{
			var ceiling = Math.Ceiling(FluentTwitter.CreateRequest()
															.Users().ShowProfileFor(person).AsJson()
															.Request().AsUser().FollowersCount / 100m);
			var results = new List<string>();
			for (var i = 1; i <= ceiling; i++)
			{
				var fileName = string.Format("getFriends_{0}_{1}.txt", person, i);
				Debug.Print(fileName);
				string feed;
				if (File.Exists(fileName))
				{
					feed = File.ReadAllText(fileName);
				}
				else
				{
					feed = FluentTwitter.CreateRequest().
						Users().GetFriends().For(person)
						.Skip(i).AsJson().Request();
					using (var stream = new StreamWriter(fileName))
					{
						stream.Write(feed);
					}
				}
				var users = feed.AsUsers();

				results.AddRange(users.Map(x => x.ScreenName));
			}

			return results;
		}

		public static string ToFileName(this string name)
		{
			var exceptionsList = new List<string>
			                     	{
			                     		"/", "\\", ":", "*", "?", '"'.ToString(), "<", ">", "|"
			                     	};
			foreach (string exc in exceptionsList)
			{
				name = Regex.Replace(name, "\\" + exc, string.Empty);
			}
			return name;
		}

		public static IEnumerable<string> GetUsersWhoTwitThis(this string word)
		{
			var fileName = string.Format("getUsersWhoTwitThis_{0}.txt", word.ToFileName());
			Debug.Print(fileName);
			XDocument feed;

			if (File.Exists(fileName))
			{
				feed = XDocument.Load(fileName);
			}
			else
			{
				string messages = FluentTwitter.CreateRequest().Search().Query().Containing(word).Take(3).AsAtom().Request();
				feed = XDocument.Parse(messages);
				feed.Save(fileName);
			}
			return feed.Root.Elements()
				.Where(x => x.Name.LocalName == "entry")
				.Elements()
				.Where(x => x.Name.LocalName == "author")
				.Elements()
				.Where(x => x.Name.LocalName == "uri")
				.ToList()
				.Map(x => x.Value.ToPersonName());
		}

		public static string ToPersonName(this string url)
		{
			return Regex.Replace(url, "http://twitter.com/", string.Empty);
		}

		public static int LoadForUser(this Dictionary<string, Dictionary<string, double>> prefs, string person)
		{
			if (!prefs.Keys.Contains(person))
				prefs[person] = new Dictionary<string, double>();

			string fileName = string.Format("loadForUser_{0}.txt", person);
			Debug.Print(fileName);
			XDocument feed;

			if (File.Exists(fileName))
			{
				feed = XDocument.Load(fileName);
			}
			else
			{
				string messages =
					FluentTwitter.CreateRequest().Search().Query().FromUser(person).AsAtom().Request();
				feed = XDocument.Parse(messages);
				feed.Save(fileName);
			}
			var entries = from x in feed.Root.Elements()
										where x.Name.LocalName == "entry"
										select x.Elements()
											.Where(element => element.Name.LocalName == "title")
											.First()
											.Value;

			foreach (string entry in entries)
			{
				foreach (string word in entry.Split(' '))
				{
					if (!prefs[person].Keys.Contains(word))
						prefs[person][word] = 0;
					prefs[person][word] += 1;
				}
			}
			return 0;
		}
	}
}